//
//  SearchOLViewController.swift
//  AutoPrint
//
//  Created by 胡玉葱 on 16/10/30.
//  Copyright © 2016年 fatcat. All rights reserved.
//

import UIKit

class SearchOLViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {

    var searchBar:UISearchBar!
    var tableView:UITableView!
    
    var searchResult:NSArray?
    var spinner:UIView! // 加载菊花
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "搜索"
        //TODO: 搜索历史
        
        searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: view.frame.width-16, height: 44))
        searchBar.placeholder = "搜索"
        searchBar.delegate = self
        searchBar.showsCancelButton = true
        
        searchBar.autocorrectionType = .No
        searchBar.autocapitalizationType = .None
        //        searchBar.returnKeyType = .Search
        //view.addSubview(searchBar)
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: searchBar)
        //navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(SearchOLViewController.dismiss))
        
        tableView = UITableView(frame: view.frame, style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = .OnDrag
        view.addSubview(tableView)
        
        // 加载菊花
        spinner = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinner.center = view.center
        spinner.backgroundColor = UIColor(white: 0, alpha: 0.75)
        spinner.layer.cornerRadius = 5
        view.addSubview(spinner)
        let actIndi = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        actIndi.center = CGPoint(x: 25, y: 25)
        actIndi.activityIndicatorViewStyle = .White
        actIndi.startAnimating()
        spinner.addSubview(actIndi)
        spinner.alpha = 0
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        searchBar.becomeFirstResponder()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchResult != nil{
            if searchResult?.count > 0{
                return searchResult!.count
            }
            return 1
        }
        return 0
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 64
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "result")
        if searchResult != nil{
            if searchResult?.count > 0{
                let thisFileItem = searchResult?.objectAtIndex(indexPath.row) as! NSDictionary
                let icon = UIImageView(frame: CGRect(x: 16, y: 8, width: 48, height: 48))
                icon.contentMode = .Center
                icon.backgroundColor = UIColor.lightGrayColor()
                cell.addSubview(icon)
                
                let nameLabel = UILabel(frame: CGRect(x: 72, y: 8, width: view.bounds.width - 80, height: 20))
                
                cell.addSubview(nameLabel)
                
                let subLabel = UILabel(frame: CGRect(x: 72, y: 36, width: view.bounds.width - 80, height: 20))
                
                subLabel.textColor = UIColor.lightGrayColor()
                cell.addSubview(subLabel)
                
                let fileName = thisFileItem.objectForKey("sourceFileName") as? String
                nameLabel.text = fileName
                subLabel.text = UDDate.shortDate(thisFileItem.objectForKey("addTime") as! String)
                
                // MARK: 文件图标
                if fileName != nil {
                    let fileType = fileName!.componentsSeparatedByString(".").last
                    if fileType != nil {
                        if fileType == "doc" || fileType == "docx" {
                            icon.backgroundColor = UIColor.clearColor()
                            icon.image = UIImage(named: "documents_icon_doc")
                        }else if fileType == "xls" || fileType == "xlsx" {
                            icon.backgroundColor = UIColor.clearColor()
                            icon.image = UIImage(named: "documents_icon_xls")
                        }else if fileType == "ppt" || fileType == "pptx" {
                            icon.backgroundColor = UIColor.clearColor()
                            icon.image = UIImage(named: "documents_icon_ppt")
                        }else if fileType == "pdf"{
                            icon.backgroundColor = UIColor.clearColor()
                            icon.image = UIImage(named: "documents_icon_pdf")
                        }else if fileType == "txt"{
                            icon.backgroundColor = UIColor.clearColor()
                            icon.image = UIImage(named: "documents_icon_txt")
                        }
                    }
                }
            }else{
                cell.textLabel?.text = "没有找到\"\(searchBar.text!)\"相关的项目"
            }
            
            
        }else{
            cell.textLabel?.text = ""
        }
        return cell
    }
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        print("search kw: \(searchBar.text)")
        // MARK: 搜索
        
        let getList = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
        getList.HTTPMethod = "POST"
        
        
        let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
        let cookiesHeader = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
        getList.setValue(cookiesHeader["Cookie"], forHTTPHeaderField: "Cookie")
        
        // TODO: 分页形式 not tested
        getList.HTTPBody = NSString(string: "act=getList&page=1&keywords=\(searchBar.text!)").dataUsingEncoding(NSUTF8StringEncoding)
        self.spinner.alpha = 1
        NSURLConnection.sendAsynchronousRequest(getList, queue: NSOperationQueue()) { (resp:NSURLResponse?, returnDara:NSData?, err:NSError?) in
            dispatch_async(dispatch_get_main_queue(), {
                self.spinner.alpha = 0
            })
            if err == nil{
                if let data = returnDara{
                    print(NSString(data: data, encoding: NSUTF8StringEncoding))
                    let jsonObj = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
                    if jsonObj != nil{
                        let jsonDic = jsonObj  as? NSDictionary
                        if jsonDic != nil{
                            let resultData = jsonDic?.objectForKey("data")
                            if resultData != nil{
                                let resultAry = resultData as? NSArray
                                if resultAry != nil{
                                    self.searchResult = NSArray(array: resultAry!)
                                    dispatch_async(dispatch_get_main_queue(), {
                                        self.tableView.reloadData()
                                    })
                                }else{
                                    self.searchResult = NSArray()
                                    dispatch_async(dispatch_get_main_queue(), {
                                        self.tableView.reloadData()
                                    })
                                }
                            }
                        }
                    }
                    
                }
            }
        }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if searchResult != nil{
            if searchResult?.count > 0{
                // 进入文件详情
                let thisRowItem = searchResult?.objectAtIndex(indexPath.row) as! NSDictionary
                let filePath = thisRowItem.objectForKey("filePath") as! String
                let fileName = thisRowItem.objectForKey("sourceFileName") as! String
                let fileMD5 = thisRowItem.objectForKey("fileMd5") as! String
                hidesBottomBarWhenPushed = true
                navigationController?.pushViewController(FileOLPreViewController(name: fileName, path: filePath, md5: fileMD5), animated: true)
            }
        }
        
    }

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        dismiss()
    }
    
    func dismiss(){
        //dismissViewControllerAnimated(true, completion: nil)
        navigationController?.popViewControllerAnimated(false)
    }
    
    /*
    func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText == "" {
            //TODO: 显示历史
        }else{
            //TODO: 显示建议
        }
    }
    */
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
